<template>
  <div>
    <a-card>
      <a-button type="primary" @click="showModal"> <PlusOutlined style="color: #ffff" />添加数据</a-button>
      <a-button style="margin-left: 15px" @click="GoReturn"><BackwardOutlined />返回</a-button>
      <!-- 新建弹框 -->
      <a-modal v-model:visible="isModalVisible" :title="modalTitle" @ok="handleOk()" @visibleChange="handleModalVisibleChange" style="width: 900px">
        <a-form :model="formState" :rules="rules"  ref="formRef" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
          <a-row :gutter="[16, 16]">
            <a-col :span="12">
              <a-form-item ref="name" label="数据名称:" name="name">
                <a-input v-model:value="formState.name" placeholder="请填写数据名称" />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="数据类型:" name="type">
                <a-select v-model:value="formState.type" placeholder="请选择数据类型">
                  <a-select-option :value="1">Boolean</a-select-option>
                  <a-select-option :value="2">Int</a-select-option>
                  <a-select-option :value="3">Float</a-select-option>
                  <a-select-option :value="4">Dounle</a-select-option>
                  <a-select-option :value="5">String</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="访问级别:" name="auth">
                <a-select v-model:value="formState.auth" placeholder="请选择访问级别">
                  <a-select-option :value="'ReadOnly'">ReadOnly</a-select-option>
                  <a-select-option :value="'ReadWrite'">ReadWrite</a-select-option>
                  <a-select-option :value="'WriteOnly'">WriteOnly</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item ref="conversionExpression" label="换算表达式:" name="conversionExpression">
                <a-input v-model:value="formState.conversionExpression" placeholder="请填写换算表达式" />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item ref="unit" label="单位:" name="unit">
                <a-input v-model:value="formState.unit" placeholder="请填写单位名称" />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="是否告警:" name="alarm">
                <a-select v-model:value="formState.alarm" placeholder="请选择是否告警">
                  <a-select-option :value="1">是</a-select-option>
                  <a-select-option :value="2">否</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="警告等级:" name="alarmLevel">
                <a-select v-model:value="formState.alarmLevel" placeholder="请选择警告等级">
                  <a-select-option :value="1">提示</a-select-option>
                  <a-select-option :value="2">次要</a-select-option>
                  <a-select-option :value="3">重要</a-select-option>
                  <a-select-option :value="4">紧急</a-select-option>
                  <a-select-option :value="5">致命</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="12" v-if="formState.alarm === 1">
              <a-form-item ref="AlarmMessage" label="告警显示信息:" name="AlarmMessage">
                <a-input v-model:value="formState.AlarmMessage" placeholder="请填写告警显示信息" />
              </a-form-item>
            </a-col>

            <a-col :span="12" v-if="formState.alarm === 1">
              <a-form-item ref="AlarmClearMessage" label="消除显示信息:" name="AlarmClearMessage">
                <a-input v-model:value="formState.AlarmClearMessage" placeholder="请填写消除显示信息" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
            <a-form-item ref="Description" label="备注:" name="Description">
              <a-textarea v-model:value="formState.Description" placeholder="请填写备注" />
            </a-form-item>
        </a-col>
          </a-row>
        </a-form>
      </a-modal>
      <a-table :dataSource="dataSources" :columns="columns" bordered style="margin-top: 5px" :custom-row="() => ({ style: { height: '35px' } })">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="EditbulletFrame(record)"><FormOutlined />编辑</a-button>
            <a-popconfirm
              title="删除"
              ok-text="确认"
              cancel-text="取消"
              description="你确定要删除吗?"
              @confirm="handleDelete(record)"
              @cancel="cancel"
            >
              <a-button type="link" danger> <DeleteOutlined style="color: red" />删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>
<script setup>
  import { ref, onMounted, reactive } from 'vue';
  import { VrtualDeviceApi } from '/@/api/system/VrtualDeviceData.js';
  import { useRouter, useRoute } from 'vue-router';
  import { message } from 'ant-design-vue';
  const route = useRoute(); // 获取当前路由
  const router = useRouter();
  const muid = route.query.muid;
  const GoReturn = () => {
    router.push({
      path: '/system/VirtualDevice/VrtualDevice',
    });
    GetVirtualModelList()
  };
  // 表格列配置
  const columns = ref([
    {
      title: '数据名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '数据类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '访问级别',
      dataIndex: 'auth',
      key: 'auth',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 200,
    },
  ]);
  const dataSources = ref([]);
  async function GetVirtualModelList() {
    const parms = {
      muid: muid,
    };
    try {
      const res = await VrtualDeviceApi.GetVirtualDeviceDataList(parms);
      console.log(res);
      dataSources.value = res.list;
    } catch (error) {
      console.error('表格数据出错', error);
    }
  }
  // 新建弹框
  const formState = reactive({
    name: '',
    auth: '',
    type: '',
    conversionExpression: '',
    unit: '',
    alarm: '',
    RecordDataCharge: '',
    RecordType: 0,
    modeltype: 20,
    Description: '',
    alarmLevel: '',
    AlarmMessage: '',
    record: null,
    AlarmClearMessage: '',
    recordInterval: 0,
    uuid: '',
  });
  const isModalVisible = ref(false);
  const showModal = () => {
      modalTitle.value = '添加触发器';
      formState.name = '';
      formState.Description = '';
      formState.AlarmClearMessage = '';
      formState.AlarmMessage = '';
      formState.alarmLevel = '';
      formState.Description = '';
      formState.RecordDataCharge = '';
      formState.RecordDataCharge = '';
      formState.alarm = '';
      formState.unit = '';
      formState.conversionExpression = '';
      formState.type = '';
      formState.auth = '';

    isModalVisible.value = true;
  };
  //   对接新增数据
  const isEditMode = ref(false); // 用于判断是否为编辑模式
  const typeMapping = {
    1: 'Boolean',
    2: 'Int',
    3: 'Float',
    4: 'Double',
    5: 'String',
  };
  const formRef = ref();
  const handleOk = async () => {
    try {
      await formRef.value.validate();
      const params = {
        type: typeMapping[formState.type], // 根据 formState.type 映射为字符串
        name: formState.name,
        Description: formState.Description,
        auth: formState.auth,
        conversionExpression: formState.conversionExpression,
        unit: formState.unit,
        alarm: formState.alarm,
        muid: muid,
        RecordDataCharge: formState.RecordDataCharge,
        RecordType: formState.RecordType,
        modeltype: formState.modeltype,
        alarmLevel: formState.alarmLevel,
        AlarmMessage: formState.AlarmMessage,
        AlarmClearMessage: formState.AlarmClearMessage,
        recordInterval: formState.recordInterval,
        record: formState.record,
      };
      const editparems = {
        data: {
          AlarmClearMessage: formState.AlarmClearMessage,
          AlarmMessage: formState.AlarmMessage,
          Description: formState.Description,
          alarm: formState.alarm,
          alarmLevel: formState.alarmLevel,
          auth: formState.auth,
          conversionExpression: formState.conversionExpression,
          name: formState.name,
          record: formState.record,
          type: typeMapping[formState.type], // 根据 formState.type 映射为字符串
          unit: formState.unit,
        },
        muid: muid,
        uuid: formState.uuid,
      };
      if (isEditMode.value) {
        // 编辑时调用编辑接口
        const res = await VrtualDeviceApi.EditVirtualDeviceData(editparems); // 这里调用编辑的API
        message.success('编辑成功');
      } else {
        const res = await VrtualDeviceApi.AddVirtualDeviceData(params);
        message.success('新建成功');
      }
      GetVirtualModelList();
      isModalVisible.value = false;
    } catch (error) {
      // 如果校验失败
      console.error('表单验证失败', error);
      message.error('请填写所有必填项');
    }
  };
  const modalTitle = ref('添加触发器');
  // // 编辑回显
  async function EditbulletFrame(record) {
    modalTitle.value = '详情'; // 点编辑时弹框标题
    isEditMode.value = true; // 设置为编辑模式
    formState.value = { ...record }; // 填充表单数据
    formState.name = record.name;
    formState.Description = record.Description;
    formState.AlarmClearMessage = record.AlarmClearMessage;
    formState.AlarmMessage = record.AlarmMessage;
    formState.alarmLevel = record.alarmLevel;
    formState.Description = record.Description;
    formState.RecordDataCharge = record.RecordDataCharge;
    formState.RecordDataCharge = record.RecordDataCharge;
    formState.alarm = record.alarm;
    formState.unit = record.unit;
    formState.conversionExpression = record.conversionExpression;
    formState.type = record.type;
    formState.auth = record.auth;
    formState.uuid = record.uuid;
    isModalVisible.value = true;
  }

  // // 删除
  async function handleDelete(record) {
    const prams = {
      uuid: record.uuid,
      muid: muid,
    };
    try {
      const res = await VrtualDeviceApi.DelVirtualDeviceData(prams);
      message.success('删除成功');
      GetVirtualModelList();
    } catch (error) {
      console.error('删除失败', error);
    }
  }
  const rules = {
    name: [
      {
        required: true,
        message: '请填写数据名称',
        trigger: 'change',
      },
    ],
    auth: [
      {
        required: true,
        message: '请选择访问级别',
        trigger: 'change',
      },
    ],
    type: [
      {
        required: true,
        message: '请选择数据类型',
        trigger: 'change',
      },
    ],

    alarm: [
      {
        required: true,
        message: '请选择是否告警',
        trigger: 'change',
      },
    ],
    alarmLevel: [
      {
        required: true,
        message: '请选择告警等级',
        trigger: 'change',
      },
    ],
    AlarmMessage: [
      {
        required: true,
        message: '请填写告警显示信息',
        trigger: 'change',
      },
    ],
  };
  onMounted(() => {
    GetVirtualModelList();
  });
</script>

<style scoped>
  .cm-editor {
    height: 100%;
  }
  .main .cm-editor {
    min-height: 300px;
  }
</style>
